﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Tilver.Api.Weixin.MP;
using Tilver.Api.Weixin.MP.CommonAPIs;
using Tilver.Data;
using Weixin.MP.BLL.AppUser;
using Weixin.MP.BLL.SysConfig;
using Weixin.MP.DAL.WeixinMP;
using Weixin.MP.UI;
using Weixin.MP.Web.Filters;

namespace Weixin.MP.Web.Controllers
{
    public class AppUserController : BaseController
    {
        // GET: /AppUser/
        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 分页显示关注用户信息
        /// </summary>
        /// <returns></returns>
        [DwzJsonException]
        public ActionResult Attention()
        {
            var pageIndex = Common.GetString("pageIndex").ToInt();
            var pageSize = Common.GetString("pageSize").ToInt();
            var recordCount = Common.GetString("recordCount").ToInt64();
            if (pageIndex <= 0) pageIndex = 1;
            if (pageSize <= 0) pageSize = Common.DefaultPageSize;

            var bo = new BLL.AppUser.AppUserBO();
            var result = bo.GetAppUsers(pageSize, pageIndex, ref recordCount);

            ViewBag.PageIndex = pageIndex;
            ViewBag.PageSize = pageSize;
            ViewBag.RecordCount = recordCount;
            return View(result);
        }

        /// <summary>
        /// 同步关注用户信息
        /// </summary>
        /// <returns></returns>
        [DwzJsonException]
        public ActionResult SyncAppUser()
        {
            /*
             当公众号关注者数量超过10000时，可通过填写next_openid的值，从而多次拉取列表的方式来满足需求。
             具体而言，就是在调用接口时，将上一次调用得到的返回中的next_openid值，作为下一次调用中的next_openid值。
             */
            var appBO = new AppUserBO();
            var accessToken = GetWeixinAccessToken();
            bool firstFlag = true;
            string nextOpenId = string.Empty;
            int callCount = 1;
            while (callCount > 0)
            {
                //获取关注者列表
                var userInfo = Tilver.Api.Weixin.MP.AdvancedAPIs.User.Get(accessToken, nextOpenId);
                int total = userInfo.total; //关注该公众账号的总用户数
                int count = userInfo.count; //拉取的OPENID个数，最大值为10000
                if (firstFlag)
                {
                    callCount = total / 10000;//需要多少次才可以把关注者列表拉取完
                    firstFlag = false;
                }
                nextOpenId = userInfo.next_openid;
                foreach (var openid in userInfo.data.openid)
                {
                    try
                    {
                        //获取关注者信息
                        var info = Tilver.Api.Weixin.MP.AdvancedAPIs.User.Info(accessToken, openid);
                        //更新或插入关注者信息
                        var tm = new TransactionManager();
                        try
                        {
                            if (appBO.GetByOpenId(info.openid, tm) == null)
                            {
                                appBO.AddAppUserInfo(new AppUserInfoEO()
                                {
                                    City = info.city,
                                    Country = info.country,
                                    Createtime = DateTime.Now,
                                    Headimgurl = info.headimgurl,
                                    Language = info.language,
                                    Nickname = info.nickname,
                                    Openid = info.openid,
                                    Province = info.province,
                                    Sex = info.sex,
                                    Subscribe = info.subscribe,
                                    SubscribeTime = info.subscribe_time
                                }, tm);
                            }
                            tm.Commit();
                        }
                        catch { tm.Rollback(); }
                    }
                    catch { }
                }
                callCount--;
            }

            return Content(Newtonsoft.Json.JsonConvert.SerializeObject(new DwzJsonResult()
            {
                StatusCode = DwzStatusCode.Ok,
                Message = string.Format("同步成功！")
            }));
        }
    }
}
